//
//  MessageViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/10/29.
//  Copyright © 2018 changqingkeji. All rights reserved.
//

import UIKit

class MessageViewController: UITableViewController {
    
    @IBOutlet weak var lineView: UIView!
    
    @IBOutlet weak var activityButton: UIButton!
    @IBOutlet weak var informButton: UIButton!
    
    var pagex: Int = 1            //默认请求第一页
    
    var data = [MessageCenter.Item]() {
        didSet {
            selectIndex = 1
        }
    }
    
    var adData = [Ad.Image]() {
        didSet {
            selectIndex = 2
        }
    }
    
    var selectIndex = 1 {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        lineView.centerX = informButton.centerX
        
        view.backgroundColor = UIColor(red: 241.00/255.00, green: 244.00/255.00, blue: 246.00/255.00, alpha: 1.0)
        let header = CustomRefreshHeader()
        tableView.gtm_addRefreshHeaderView(refreshHeader: header) { [weak self] in
            if self?.selectIndex == 1 {
                self?.requestData(isMore: false)
            } else {
                self?.requestAd()
            }
        }
        
        let footer = CustomRefreshFooter()
        
        tableView.gtm_addLoadMoreFooterView(loadMoreFooter: footer) { [weak self] in
            if self?.selectIndex == 1 {
                self?.requestData(isMore: true)
            } else {
                self?.tableView.endRefreshing(isSuccess: true)
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //立即刷新
        self.tableView.triggerRefreshing()
    }
    
    func requestData(isMore: Bool) {
        
        pagex = isMore ? pagex + 1 : 1
        JZLoading.showLoadingWith(toView: self.view)
        
        MessageCenter.getMessage(page: pagex, pageSize: 10, success: { [weak self] data in
            JZLoading.hideLoading()
            guard let self = self, let data = data else {
                return
            }
            
            self.tableView.endRefreshing(isSuccess: true)
            
            self.data = isMore ? self.data + data : data
            
            UIView.removeStatusView()
            
            if self.data.count == 0 {
                UIView.showInfoViewWithEmpty(self.view, text: "暂无消息")
            }
        }) { [weak self] error in
            self?.tableView.endRefreshing(isSuccess: true)
            JZLoading.hideLoading()
            self?.showError(error)
        }
    }
    
    func requestAd() {
        JZLoading.showLoadingWith(toView: self.view)
        
        Ad.ad(success: { [weak self] data in
            JZLoading.hideLoading()
            
            guard let self = self, let data = data else {
                return
            }
            
            self.tableView.endRefreshing(isSuccess: true)
            
            self.adData = data.list
            
            UIView.removeStatusView()
            
            if self.adData.count == 0 {
                UIView.showInfoViewWithEmpty(self.view, text: "暂无消息")
            }
        }) { [weak self] msg in
            self?.tableView.endRefreshing(isSuccess: true)
            JZLoading.hideLoading()
            self?.showError(msg)
        }
    }
    
    @IBAction func inform(_ sender: UIButton) {
        UIView.animate(withDuration: 0.25) { [weak self] in
            self?.lineView.centerX = sender.centerX
        }
        
        activityButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        
        requestData(isMore: false)
    }
    
    @IBAction func activity(_ sender: UIButton) {
        UIView.animate(withDuration: 0.25) { [weak self] in
            self?.lineView.centerX = sender.centerX
        }
        
        informButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        sender.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        
        requestAd()
    }
    
    // MARK: - Table view data source
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return selectIndex == 1 ? data.count : adData.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identifier = selectIndex == 1 ? "cell" : "cell2"
        let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
        
        if let cell = cell as? MessageCenterCell {
            let item = self.data[indexPath.row]
            cell.timeLabel.text = Date.timeStampToString(timeStamp: item.createdAt)
            cell.contentLabel.text = item.messageContent
        } else if let cell = cell as? AdCell {
            let item = self.adData[indexPath.row]
            
            let time = Date(timeIntervalSince1970: TimeInterval(item.onlineTime))
            let url = URL(string: kImageServerName + item.appImagePath)
            
            cell.onlineTimeLabel.text = Date.dateConvertString(date: time)
            cell.shareTitleLabel.text = item.adName
            cell.appImagePathImage.kf.setImage(with: url)
        }
        
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard selectIndex == 2 else {
            return
        }
        let item = self.adData[indexPath.row]
        self.performSegue(withIdentifier: "webViewSegue", sender: item)
    }
    
    // MARK: - Navigation
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "webViewSegue" {  //web
            if let nav = segue.destination as? UINavigationController,
                let vc = nav.viewControllers.first as? WebViewController,
                let shareInfo = sender as? Ad.Image {
                vc.page = Page.other(shareInfo)
            }
        }
    }
}

